import urllib2

class BrowserError(Exception):
    pass


class Browser(object):
    """
    Create 'browser'
    """
    def __init__(self, 
        user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3',
        proxy = None
    ):
        handlers = []
        if proxy:  
            handlers.append(urllib2.ProxyHandler(proxy))
            
        self.opener = urllib2.build_opener(*handlers)
        self.opener.addheaders = [('User-agent', user_agent)]
        
        self.current_url = None
        self.current_content = None
        
    def open(self, url):
        """
        Open url and return page content
        """
        try:
            c = self.opener.open(url)
            content = c.read()
        except urllib2.HTTPError, error:
            raise Exception, "[HTTP Error %s] %s, on %s]" % (error.code, error.msg, url)

        self.current_url = url   
        self.current_content = content   
             
        return self.current_content
    
    def save(self, filename):
        """
        Save last opened page to file
        """
        if self.current_content is None:
            raise BrowserError('No pages was opened!')
        open(filename, 'w').write(self.current_content)        

